#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SNMP_util;
use SIM_cgi;
use SIM_base;
use SIM_settings;
use SIM_nodeInfo;

my $configDir = $SIMparam{'SIMtunixBupcfgData'};

#BEGIN { $Exporter::Verbose=1 }

# Startupscript translater
my $tool = $ARGV[0];
my $vendor = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];

my $httpScriptName = $ENV{'SCRIPT_NAME'};

# SNMP settings to prevent error logging.
$SNMP_Session::suppress_warnings = 1000;

sub listDevices {
  print("<TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR BGCOLOR=#EEEEEE><TD ALIGN=center>");
  my $option1 = $_[0];
  chdir "$configDir";
  my @devices = <*>;
  foreach my $entry (@devices) {
    print(". <A HREF=$httpScriptName?$tool+$vendor+listEntries+$entry>$entry</A> .");
  }
  print("</TD></TR></TABLE>");
}

sub listEntries {
  my $option1 = $_[0];
  my $option2 = $_[1];
  if ( -d "$configDir/$option1") {
    chdir "$configDir";
    my $searchStr = "$option1/$option2";
    if ( $option2 eq "" ) {
      $searchStr = $option1;
    }
#   print("<TR><TD>Search $searchStr</TD></TR>");
    my @fileList = <$searchStr/*>;
    if ( $option2 eq "" ) {
      print("<H4>Listing entries for $option1</H4>");
      print("<TABLE>");
    }
    foreach my $name (@fileList) {
      my ( $devName, $dirInfo ) = split('\/', $name, 2);
      if ( -d $name ) {
        &listEntries($option1, $dirInfo);
#       print("<TR><TD>Dir $name</TD></TR>");
      } elsif (( -f $name ) and ( -r $name )) {
        print("<TR><TD>$devName/<A HREF=$httpScriptName?$tool+$vendor+printFile+$devName+$dirInfo>$dirInfo</TD></TR>");
      }
    }
    if ( $option2 eq "" ) {
      print("</TABLE>");
    }
  }
}
  
sub printFile {
  my $option1 = $_[0];
  my $option2 = $_[1];
  print("<H4>$option1 ==&gt; $option2</H4>");
  my $file = "$option1/$option2";
  if (( -f $file ) and ( -r $file )) {
    open(IN, $file);
    my @info = <IN>;
    close IN;
    print("<TABLE><TR><TD><PRE>");
    foreach my $line (@info) {
      print("$line");
    }
    print("</PRE></TD></TR></TABLE>");
  }
}

#--------------------------- Main ---------------------------
# most scripts will be hostname based, because devices can change dynamically from controller.
print("<CENTER>");
&listDevices;

if ( $action eq "listFiles" ) {
  &listFiles;
} elsif ( $action eq "listEntries" ) {
  &listEntries($option1);
} elsif ( $action eq "printFile" ) {
  &printFile($option1,$option2);
} else {
  print("<H2>Choose an device above.</H2>");;
}
